package com.guqj.nio.netty.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Title TcpClient
 * @Description netty tcp粘包客户端
 * @date 2016年11月17日
 */
public class TcpClient {

	/**
	 * @Description 连接服务端
	 * @param host
	 * @param port
	 * @throws InterruptedException
	 */
	public void connet(String host, int port) throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ClientChannelInitializer());

			Channel c = b.connect(host, port).sync().channel();
			System.out.println(String.format("客户端已连接服务端：[%s:%s]", host, port));
			c.closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}

	class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			// 分隔符解码器
			//ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
			//ch.pipeline().addLast(new DelimiterBasedFrameDecoder(4096, delimiter));
			// 换行解码器  \r \r\n
			//ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
			// 固定长度解码器
			ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
			ch.pipeline().addLast(new StringDecoder());
			ch.pipeline().addLast(new TcpClientHandler());
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		new TcpClient().connet("localhost", 11013);
	}
}
